#include "TcpServer.hpp"
#include "HttpParse.hpp"
#include <fstream>
#include <memory>

void Useage(const std::string& str)
{
    std::cout << "Useage:\n\t" << str << " port \n";
    exit(USE_ERR);
}

std::string OpenFile(const std::string& filename)
{
    std::ifstream ifs(filename.c_str(), std::ios::in);
    if(!ifs.is_open())
        return "";
    char ch;
    std::string message;
    while(ifs >> ch)
    {
        message += ch;
    }
    return message;
}

class HttpService
{
public:
    HttpService(){}
    ~HttpService(){}
    void Service(sock_sptr sptr, InetAddr addr)
    {
        std::string inbuffer;
        while(true)
        {
            //1.获取request
            int n = sptr->Recv(inbuffer);
            if(n <= 0)
                break;

            LOG(INFO, "inbuffer : %s\n", inbuffer.c_str());
            // 2.报文解析，判断是否是一个完整的报文
            std::string message;
            while((message = DeCode()(inbuffer)) != "")
            {
                //3. 反序列化
                Request req;
                req.DeSerialize(message);
                //4. 填充response
                // Response res;
                // res.AddStatus(200);
                // res.AddContentType(req.suffix());
                // res.AddContent(OpenFile(req.path()));

                Response res;
                res.AddStatus(301);
                res.Addkv("Location", "https://www.baidu.com");
                // res.Addkv("referer", "https://www.qq.com");

                //5. 序列化
                std::string out;
                res.Serialize(out);
                std::cout << out << std::endl;

                //6. 发送
                sptr->Send(out);
            }
        }
    };
};




int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Useage(argv[0]);
    }

    uint16_t port = std::stoi(argv[1]);

    HttpService hs;
    std::unique_ptr<TcpServer> usvr = std::make_unique<TcpServer>(port, std::bind(&HttpService::Service, &hs, std::placeholders::_1, std::placeholders::_2));
    usvr->Loop();

    return 0;
}